import process from 'node:process';
import path from 'node:path';
import { fileURLToPath } from 'node:url'
import { normalizePath } from 'vite'
import ps from "ps-node"
import robot from "robotjs"

function getPidByProcessName(processName: string) {
  return new Promise((resolve, reject) => {
    ps.lookup({ command: processName }, (err: any, resultList: any) => {
      if (err) {
        return reject(err);
      }

      if (resultList.length > 0) {
        resolve(resultList[0].pid);
      } else {
        resolve(null);
      }
    });
  });
}


export const DEFAULT_INSPECTOR_OPTIONS = {

} as const


let virtualMusicModuleId = "virtual:vue-music-play"
let resolvedMusicVirtualModuleId = '\0' + virtualMusicModuleId;


async function VitePluginInspector(options: any = DEFAULT_INSPECTOR_OPTIONS) {
  const normalizedOptions = {
    ...DEFAULT_INSPECTOR_OPTIONS,
    ...options,
  }
  let config: any
  let existCloud = await getPidByProcessName("cloudmusic")


  if (normalizedOptions.launchEditor)
    process.env.LAUNCH_EDITOR = normalizedOptions.launchEditor

  return [
    {
      name: 'vite-plugin-vue-inspector',
      enforce: 'pre',
      apply(_: any, { command }: any) {
        // apply only on serve and not for test
        return command === 'serve' && process.env.NODE_ENV !== 'test'
      },
      async resolveId(importee: string) {


        if (importee === (virtualMusicModuleId)) {

          const resolved = resolvedMusicVirtualModuleId
          return resolved
        }
      },

      async load(id: any) {

        if (id === resolvedMusicVirtualModuleId) {



          return `export const existCloud=${JSON.stringify(existCloud)}`
        }

      },

      configureServer(server: any) {
        class MusicEvent {
          private changeHandler(playstr: string) {
            robot.keyToggle("control", "down");
            robot.keyToggle("alt", "down");
            // 模拟按下 Tab 键
            robot.keyTap(playstr);
            setTimeout(() => {
              robot.keyToggle("alt", "up");
              robot.keyToggle("control", "up");
            }, 100);
          }
          pre() {
            this.changeHandler('left')
          }
          pause() {
         
            this.changeHandler('p')
          }
          play() {
          
            this.changeHandler('p')
          }
          next() {
          
            this.changeHandler('right')
          }
        }
        type MusicEventKeys = keyof MusicEvent;

        let musicEvent = new MusicEvent()
        server.ws.on('music', (payload: { msg: MusicEventKeys }) => {
          // console.log(payload.msg)
          musicEvent[payload.msg]()
        })
      },
      config: (config: any, env: any) => {
        // 在这里修改配置
        return {

        };
      },
      transform(code: any, id: any) {

      },
      // transformIndexHtml(html: any) {

      //   const start = Date.now();

      //   if (appendTo)
      //     return
      //   return {
      //     html,
      //     tags: [
      //       {
      //         tag: 'script',
      //         injectTo: 'head',
      //         attrs: {
      //           type: "module",
      //           src: `/${virtualMusicModuleId}`,
      //         },

      //       },

      //     ],
      //   }
      // },
      configResolved(resolvedConfig: any) {
        config = resolvedConfig
      },
    },

  ]
}
export default VitePluginInspector